package com.yidi.system.service.imp;

import com.yidi.common.annotation.DataScope;
import com.yidi.common.constant.UserConstants;
import com.yidi.common.core.domain.entity.SysDept;
import com.yidi.common.core.domain.entity.SysRole;
import com.yidi.common.core.domain.entity.SysUser;
import com.yidi.common.core.page.MyPage;
import com.yidi.common.core.service.imp.AbstractBaseService;
import com.yidi.common.exception.ServiceException;
import com.yidi.common.utils.SecurityUtils;
import com.yidi.common.utils.StringUtils;
import com.yidi.common.utils.spring.SpringUtils;
import com.yidi.system.domain.SysPost;
import com.yidi.system.domain.SysUserPost;
import com.yidi.system.domain.SysUserRole;
import com.yidi.system.repository.SysUserRepository;
import com.yidi.system.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.transaction.Transactional;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author ：Xn
 * @ClassName: SysUserServiceImpl
 * @date ：2021-10-19 14:40
 * @describe ：
 */
@Service
public class SysUserServiceImpl extends AbstractBaseService<SysUser> implements SysUserService {

    private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);

    @Autowired
    private SysUserRepository sysUserRepository;
    @Autowired
    private SysConfigService configService;
    @Autowired
    private SysUserRoleService userRoleService;
    @Autowired
    private SysUserPostService userPostService;
    @Autowired
    private SysDeptService sysDeptService;
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysPostService sysPostService;

    @PersistenceContext
    private EntityManager em;

    /**
     * 根据条件分页查询用户列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public MyPage<SysUser> selectUserList( SysUser user, Integer pageNo, Integer pageSize)
    {
        StringBuilder sql = new StringBuilder(
                "select u.id, u.dept_id, u.nick_name as nickName, u.user_name as userName, u.email, u.avatar, u.phonenumber, u.password, u.sex, u.status, u.remove_status as removeStatus, u.login_ip as loginIp, u.login_date, u.create_by, u.create_time, u.remark, d.dept_name as deptName, d.leader from sys_user u" +
                        " left join sys_dept d on u.dept_id = d.id" +
                        " where u.remove_status = '0'");
        if(user.getId() != null){
            sql.append(" and u.id = ").append(user.getId());
        }
        if(StringUtils.isNotBlank(user.getUserName())){
            sql.append(" and u.user_name like concat('%','").append(user.getUserName()).append("', '%')");
        }
        if(StringUtils.isNotBlank(user.getStatus())){
            sql.append(" and u.status = ").append(user.getStatus());
        }
        if(StringUtils.isNotBlank(user.getPhonenumber())){
            sql.append(" and u.phonenumber like concat('%',").append(user.getPhonenumber()).append(", '%')");
        }
        if(user.getDeptId() != null){
            sql.append(" and (u.dept_id = ").append(user.getDeptId()).append(" or u.dept_id in ( select t.id from sys_dept t where find_in_set(").append(user.getDeptId()).append(", ancestors) ))");
        }
        if(user.getParams() != null){
            Map<String, Object> params = user.getParams();
            String beginTime = (String) params.get("beginTime");
            String endTime = (String) params.get("endTime");
            String sqlString = (String)params.get("dataScope");

            if(StringUtils.isNotBlank(beginTime)){
                sql.append(" and date_format(r.create_time,'%y%m%d') >= date_format('").append(beginTime).append("','%y%m%d')");
            }
            if(StringUtils.isNotBlank(endTime)){
                sql.append(" and date_format(r.create_time,'%y%m%d') <= date_format('").append(endTime).append("','%y%m%d')");
            }
            if(StringUtils.isNotBlank(sqlString)){
                sql.append(sqlString);
            }
        }

        Query query = em.createNativeQuery(sql.toString());
        int firstIndex = pageNo * pageSize;
        query.setFirstResult(firstIndex);
        query.setMaxResults(pageSize);
        List<Object[]> list = query.getResultList();
        String countSql = "select count(*) from ("+sql.toString()+") c";
        Query countQuery = em.createNativeQuery(countSql);
        Object obj = countQuery.getSingleResult();
        Integer tatal = Integer.parseInt(obj.toString());
        BigDecimal bd = BigDecimal.valueOf(tatal);
        BigDecimal bdsize = BigDecimal.valueOf(pageSize);
        BigDecimal bdvi = bd.divide(bdsize, 1, BigDecimal.ROUND_HALF_UP);
        Integer totalPage = (int)Math.ceil(bdvi.doubleValue());
        List<SysUser> userList = new ArrayList<SysUser>();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        for(Object[] objects : list){
            SysUser u = new SysUser();
            u.setId(Long.parseLong(objects[0].toString()));
            u.setDeptId(objects[1] == null ? null : Long.parseLong(objects[1].toString()));
            u.setNickName(objects[2].toString());
            u.setUserName(objects[3].toString());
            u.setEmail(objects[4].toString());
            u.setAvatar(objects[5] == null ? "" : objects[5].toString());
            u.setPhonenumber(objects[6].toString());
            u.setSex(objects[8].toString());
            u.setStatus(objects[9].toString());
            u.setRemoveStatus(objects[10] == null ? null : Integer.parseInt(objects[10].toString()));
            u.setLoginIp(objects[11] == null ? "" : objects[11].toString());

            try {
                u.setLoginDate(objects[12] == null ? null : format.parse(objects[12].toString()));
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            try {
                u.setCreateTime(objects[14] == null ? null : format.parse(objects[14].toString()));
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            SysDept sd = new SysDept();
            if(objects[16] != null){
                sd.setDeptName(objects[16].toString());
            }
            if(objects[17] != null){
                sd.setLeader(objects[17].toString());
            }
            u.setDept(sd);
            userList.add(u);
        }
        MyPage<SysUser> page = new MyPage<SysUser>(pageNo,totalPage,userList,new com.yidi.common.core.page.Pageable(pageSize),tatal+"",tatal);
        return page;
    }

    /**
     * 通过用户名查询用户
     *
     * @param userName 用户名
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserByUserName(String userName)
    {

        SysUser user = sysUserRepository.findByUserName(userName);
        if(user.getDeptId() != null){
            SysDept dept = sysDeptService.findById(user.getDeptId());
            user.setDept(dept);
        }
        List<SysUserRole> urList = userRoleService.findByUserId(user.getId());
        List<SysRole> rList = new ArrayList<>();
        for(SysUserRole ur : urList){
            SysRole r = sysRoleService.findById(ur.getRoleId());
            rList.add(r);
        }
        if(rList.size() > 0){
            user.setRoles(rList);
        }

        return user;
    }

    /**
     * 根据条件分页查询已分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public MyPage<SysUser> selectAllocatedList(SysUser user, Integer pageNum,Integer pageSize)
    {
        StringBuilder sql = new StringBuilder(
                "select distinct u.id, u.dept_id as deptId, u.user_name as userName, u.nick_name as nickName, u.email, u.phonenumber, u.status, u.create_time as createTime from sys_user u" +
                        " left join sys_dept d on u.dept_id = d.id" +
                        " left join sys_user_role ur on u.id = ur.user_id" +
                        " left join sys_role r on r.id = ur.role_id" +
                        " where u.remove_status = 0");
        if(user.getRoleId() != null){
            sql.append(" and r.id = ").append(user.getRoleId());
        }
        if(StringUtils.isNotBlank(user.getUserName())){
            sql.append(" and u.user_name like concat('%','").append(user.getUserName()).append("', '%')");
        }
        if(StringUtils.isNotBlank(user.getPhonenumber())){
            sql.append(" and u.phonenumber like concat('%','").append(user.getPhonenumber()).append("', '%')");
        }
        if(user.getParams() != null){
            Map<String, Object> params = user.getParams();
            String sqlString = (String)params.get("dataScope");

            if(StringUtils.isNotBlank(sqlString)){
                sql.append(sqlString);
            }
        }
        Query query = em.createNativeQuery(sql.toString());
        int firstIndex = pageNum * pageSize;
        query.setFirstResult(firstIndex);
        query.setMaxResults(pageSize);
        List<Object[]> list = query.getResultList();
        String countSql = "select count(*) from ("+sql.toString()+") c";
        Query countQuery = em.createNativeQuery(countSql);
        Object obj = countQuery.getSingleResult();
        Integer tatal = Integer.parseInt(obj.toString());
        BigDecimal bd = BigDecimal.valueOf(tatal);
        BigDecimal bdsize = BigDecimal.valueOf(pageSize);
        BigDecimal bdvi = bd.divide(bdsize, 1, BigDecimal.ROUND_HALF_UP);
        Integer totalPage = (int)Math.ceil(bdvi.doubleValue());
        List<SysUser> list1 = new ArrayList<SysUser>();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        for(Object[] objects : list){
            SysUser u = new SysUser();
            u.setId(Long.parseLong(objects[0].toString()));
            u.setDeptId(objects[1] == null ? null : Long.parseLong(objects[1].toString()));
            u.setNickName(objects[2].toString());
            u.setUserName(objects[3].toString());
            u.setEmail(objects[4].toString());
            u.setPhonenumber(objects[5].toString());
            u.setStatus(objects[6].toString());
            try {
                u.setCreateTime(format.parse(objects[7].toString()));
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            list1.add(u);
        }
        MyPage<SysUser> page = new MyPage<SysUser>(0,totalPage,list1,new com.yidi.common.core.page.Pageable(Integer.MAX_VALUE),tatal+"",tatal);
        return page;
    }

    /**
     * 根据条件分页查询未分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public MyPage<SysUser> selectUnallocatedList(SysUser user, Integer pageNum,Integer pageSize)
    {
        StringBuilder sql = new StringBuilder(
                "select distinct u.id, u.dept_id as deptId, u.user_name as userName, u.nick_name as nickName, u.email, u.phonenumber, u.status, u.create_time as createTime from sys_user u" +
                        " left join sys_dept d on u.dept_id = d.id" +
                        " left join sys_user_role ur on u.id = ur.user_id" +
                        " left join sys_role r on r.id = ur.role_id" +
                        " where u.remove_status = 0 and u.user_name != 'admin'");
        if(user.getRoleId() != null){
            sql.append(" and ( r.id != ").append(user.getRoleId()).append(" or r.id IS NULL)");
            sql.append(" and u.id not in (select u.id from sys_user u inner join sys_user_role ur on u.id = ur.user_id and ur.role_id = ").append(user.getRoleId()).append(")");
        }
        if(StringUtils.isNotBlank(user.getUserName())){
            sql.append(" and u.user_name like concat('%','").append(user.getUserName()).append("', '%')");
        }
        if(StringUtils.isNotBlank(user.getPhonenumber())){
            sql.append(" and u.phonenumber like concat('%','").append(user.getPhonenumber()).append("', '%')");
        }
        if(user.getParams() != null){
            Map<String, Object> params = user.getParams();
            String sqlString = (String)params.get("dataScope");

            if(StringUtils.isNotBlank(sqlString)){
                sql.append(sqlString);
            }
        }

        Query query = em.createNativeQuery(sql.toString());
        int firstIndex = pageNum * pageSize;
        query.setFirstResult(firstIndex);
        query.setMaxResults(pageSize);
        List<Object[]> list = query.getResultList();
        String countSql = "select count(*) from ("+sql.toString()+") c";
        Query countQuery = em.createNativeQuery(countSql);
        Object obj = countQuery.getSingleResult();
        Integer tatal = Integer.parseInt(obj.toString());
        BigDecimal bd = BigDecimal.valueOf(tatal);
        BigDecimal bdsize = BigDecimal.valueOf(pageSize);
        BigDecimal bdvi = bd.divide(bdsize, 1, BigDecimal.ROUND_HALF_UP);
        Integer totalPage = (int)Math.ceil(bdvi.doubleValue());
        List<SysUser> list1 = new ArrayList<SysUser>();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        for(Object[] objects : list){
            SysUser u = new SysUser();
            u.setId(Long.parseLong(objects[0].toString()));
            u.setDeptId(objects[1] == null ? null : Long.parseLong(objects[1].toString()));
            u.setNickName(objects[2].toString());
            u.setUserName(objects[3].toString());
            u.setEmail(objects[4].toString());
            u.setPhonenumber(objects[5].toString());
            u.setStatus(objects[6].toString());
            try {
                u.setCreateTime(format.parse(objects[7].toString()));
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            list1.add(u);
        }
        MyPage<SysUser> page = new MyPage<SysUser>(0,totalPage,list1,new com.yidi.common.core.page.Pageable(Integer.MAX_VALUE),tatal+"",tatal);
        return page;
    }

    /**
     * 校验用户是否有数据权限
     *
     * @param userId 用户id
     */
    @Override
    public void checkUserDataScope(Long userId)
    {
        SysUser u = findById(SecurityUtils.getUserId());
        if (!SysUser.isAdmin(u.getUserName()))
        {
            SysUser user = new SysUser();
            user.setId(userId);
            List<SysUser> users = SpringUtils.getAopProxy(this).selectUserList(user,0,Integer.MAX_VALUE).getContent();
            if (StringUtils.isEmpty(users))
            {
                throw new ServiceException("没有权限访问用户数据！");
            }
        }
    }

    /**
     * 导入用户数据
     *
     * @param userList 用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importUser(List<SysUser> userList, Boolean isUpdateSupport, String operName)
    {
        if (StringUtils.isNull(userList) || userList.size() == 0)
        {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        String password = configService.selectConfigByKey("sys.user.initPassword");
        for (SysUser user : userList)
        {
            try
            {
                // 验证是否存在这个用户
                SysUser u = sysUserRepository.findByUserName(user.getUserName());
                if (StringUtils.isNull(u))
                {
                    user.setPassword(SecurityUtils.encryptPassword(password));
                    user.setCreateBy(operName);
                    add(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
                    user.setUpdateBy(operName);
                    modify(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、账号 " + user.getUserName() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + user.getUserName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 校验用户名称是否唯一
     *
     * @param userName 用户名称
     * @return 结果
     */
    @Override
    public String checkUserNameUnique(String userName)
    {
        int count = sysUserRepository.checkUserNameUnique(userName);
        if (count > 0)
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验用户名称是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public String checkPhoneUnique(SysUser user)
    {
        Long userId = StringUtils.isNull(user.getId()) ? -1L : user.getId();
        SysUser info = sysUserRepository.findByPhonenumber(user.getPhonenumber());
        if (StringUtils.isNotNull(info) && !info.getId().equals(userId))
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验email是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public String checkEmailUnique(SysUser user)
    {
        Long userId = StringUtils.isNull(user.getId()) ? -1L : user.getId();
        SysUser info = sysUserRepository.findByEmail(user.getEmail());
        if (StringUtils.isNotNull(info) && !info.getId().equals(userId))
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 查询用户所属角色组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserRoleGroup(String userName) {
        StringBuilder sql = new StringBuilder(
                "select distinct r.id, r.role_name, r.role_key, r.order_num, r.data_scope, r.menu_check_strictly, r.dept_check_strictly, r.status, r.remove_status, r.create_time, r.remark from sys_role r" +
                        " left join sys_user_role ur on ur.role_id = r.id" +
                        " left join sys_user u on u.id = ur.user_id" +
                        " left join sys_dept d on u.dept_id = d.id" +
                        " where r.remove_status = 0");
        if(StringUtils.isNotBlank(userName)){
            sql.append(" and u.user_name = '").append(userName).append("'");
        }
        Query query = em.createNativeQuery(sql.toString());
        List<Object[]> list = query.getResultList();
        List<SysRole> roleList = new ArrayList<SysRole>();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        for(Object[] objects : list){
            SysRole sr = new SysRole();
            sr.setId(Long.parseLong(objects[0].toString()));
            sr.setRoleName(objects[1].toString());
            sr.setRoleKey(objects[2].toString());
            sr.setOrderNum(Integer.valueOf(objects[3].toString()));
            sr.setDataScope(objects[4].toString());
            sr.setMenuCheckStrictly(Boolean.valueOf(objects[5].toString()));
            sr.setDeptCheckStrictly(Boolean.valueOf(objects[6].toString()));
            sr.setStatus(objects[7].toString());
            sr.setRemoveStatus(Integer.valueOf(objects[8].toString()));
            try {
                sr.setCreateTime(format.parse(objects[9].toString()));
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            if(objects[10] != null){
                sr.setRemark(objects[10].toString());
            }
            roleList.add(sr);
        }

        StringBuffer idsStr = new StringBuffer();
        for (SysRole role : roleList)
        {
            idsStr.append(role.getRoleName()).append(",");
        }
        if (StringUtils.isNotEmpty(idsStr.toString()))
        {
            return idsStr.substring(0, idsStr.length() - 1);
        }
        return idsStr.toString();
    }

    /**
     * 查询用户所属岗位组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserPostGroup(String userName) {
        List<SysPost> list = sysPostService.selectPostsByUserName(userName);
        StringBuffer idsStr = new StringBuffer();
        for (SysPost post : list)
        {
            idsStr.append(post.getPostName()).append(",");
        }
        if (StringUtils.isNotEmpty(idsStr.toString()))
        {
            return idsStr.substring(0, idsStr.length() - 1);
        }
        return idsStr.toString();
    }

    /**
     * 校验用户是否允许操作
     *
     * @param user 用户信息
     */
    @Override
    public void checkUserAllowed(SysUser user)
    {
        if (StringUtils.isNotNull(user.getId()) && user.isAdmin())
        {
            throw new ServiceException("不允许操作超级管理员用户");
        }
    }

    @Override
    public void insertUser(SysUser user) {
        add(user);
        // 新增用户与角色管理
        insertUserRole(user.getId(), user.getRoleIds());
        // 新增用户与岗位管理
        insertUserPost(user);
    }

    /**
     * 修改保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public void updateUser(SysUser user)
    {
        SysUser u = findById(user.getId());
        u.setNickName(user.getNickName());
        u.setDeptId(user.getDeptId());
        u.setPhonenumber(user.getPhonenumber());
        u.setEmail(user.getEmail());
        u.setStatus(user.getStatus());
        u.setSex(user.getSex());
        u.setRemark(user.getRemark());

        // 删除用户与角色关联
        userRoleService.deleteUserRoleByUserId(user.getId());
        // 新增用户与角色管理
        insertUserRole(user.getId(), user.getRoleIds());
        // 删除用户与岗位关联
        userPostService.deleteUserPostByUserId(user.getId());
        // 新增用户与岗位管理
        insertUserPost(user);
        modify(u);
    }

    /**
     * 批量删除用户信息
     *
     * @param userIds 需要删除的用户ID
     * @return 结果
     */
    @Override
    @Transactional
    public void deleteUserByIds(Long[] userIds)
    {
        for (Long userId : userIds)
        {
            checkUserAllowed(new SysUser(userId));
        }
        // 删除用户与角色关联
        userRoleService.deleteUserRole(userIds);
        // 删除用户与岗位关联
        userPostService.deleteUserPost(userIds);
        for(Long id : userIds){
            delete(id);
        }
    }

    @Override
    public void resetPwd(SysUser sysUser){
        SysUser u = findById(sysUser.getId());
        u.setPassword(sysUser.getPassword());
        modify(u);
    }

    /**
     * 修改密码
     *
     * @param userName 用户名
     * @param password 密码
     * @return 结果
     */
    @Override
    public void resetUserPwd(String userName, String password)
    {
        SysUser user = sysUserRepository.findByUserName(userName);
        user.setPassword(password);
        modify(user);
    }

    /**
     * 修改用户状态
     * @param sysUser
     */
    @Override
    public void updateUserStatus(SysUser sysUser){
        SysUser u = findById(sysUser.getId());
        u.setStatus(sysUser.getStatus());
        modify(u);
    }

    /**
     * 修改头像
     * @param userName
     * @param avatar
     */
    @Override
    public void updateUserAvatar(String userName, String avatar) {
        SysUser user = sysUserRepository.findByUserName(userName);
        user.setAvatar(avatar);
        modify(user);
    }

    /**
     * 用户授权角色
     *
     * @param userId 用户ID
     * @param roleIds 角色组
     */
    @Override
    @Transactional
    public void insertUserAuth(Long userId, Long[] roleIds)
    {
        userRoleService.deleteUserRoleByUserId(userId);
        insertUserRole(userId, roleIds);
    }

    /**
     * 个人信息-修改
     * @param sysUser
     */
    @Override
    public void updateUserProfile(SysUser sysUser){
        SysUser u = findById(sysUser.getId());
        u.setNickName(sysUser.getNickName());
        u.setPhonenumber(sysUser.getPhonenumber());
        u.setEmail(sysUser.getEmail());
        u.setSex(sysUser.getSex());
        u.setUpdateTime(new Date());
        modify(u);
    }

    /**
     * 更新个人登录IP
     */
    @Override
    public void updateUserLoginIp(SysUser sysUser){
        SysUser u = findById(sysUser.getId());
        u.setLoginIp(sysUser.getLoginIp());
        u.setLoginDate(sysUser.getLoginDate());
        sysUserRepository.save(u);
    }

    /**
     * 注册用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean registerUser(SysUser user)
    {
        String result = checkUserNameUnique(user.getUserName());
        if(result.equals(UserConstants.UNIQUE)){
            add(user);
            return true;
        }else{
            return false;
        }
    }

    /**
     * 新增用户角色信息
     *
     */
    public void insertUserRole(Long userId, Long[] roleIds)
    {
        if (StringUtils.isNotNull(roleIds))
        {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>();
            for (Long roleId : roleIds)
            {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(userId);
                ur.setRoleId(roleId);
                list.add(ur);
            }
            if (list.size() > 0)
            {
                userRoleService.batchUserRole(list);
            }
        }
    }

    /**
     * 新增用户岗位信息
     *
     * @param user 用户对象
     */
    public void insertUserPost(SysUser user)
    {
        Long[] posts = user.getPostIds();
        if (StringUtils.isNotNull(posts))
        {
            // 新增用户与岗位管理
            List<SysUserPost> list = new ArrayList<SysUserPost>();
            for (Long postId : user.getPostIds())
            {
                SysUserPost up = new SysUserPost();
                up.setUserId(user.getId());
                up.setPostId(postId);
                list.add(up);
            }
            if (list.size() > 0)
            {
                userPostService.batchUserPost(list);
            }
        }
    }

    public List<SysUser> mapChangeMenus(List<Map<String, Object>> menuMap){

        List<SysUser> userList  = new LinkedList<SysUser>();

        for(int i = 0; i < menuMap.size(); i++) {
            Map<String, Object> map = menuMap.get(i);
            SysUser u = new SysUser();
            u.setId(Long.valueOf(String.valueOf(map.get("id"))));
            u.setDeptId(Long.valueOf(String.valueOf(map.get("deptId"))));
            u.setUserName(String.valueOf(map.get("userName")));
            u.setNickName(String.valueOf(map.get("nickName")));
            u.setEmail(String.valueOf(map.get("email")));
            u.setPhonenumber(String.valueOf(map.get("phonenumber")));
            u.setStatus(String.valueOf(map.get("status")));
            userList.add(u);
        }

        return userList;
    }
}
